package flex.cc.sms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import flex.cc.PublicUtil;
import flex.cc.common.utils.SendSmsUtil;
import flex.cc.core.utils.RequestUtil;
import flex.cc.order.manage.dao.OrderCustomerDao;
import flex.cc.order.manage.dto.order.OrderCustomerEntity;
import flex.cc.order.manage.dto.order.OrderMainEntity;
import flex.cc.sms.dao.SmsInfoDao;
import flex.cc.sms.dto.SmsInfoEntity;
import flex.cc.sms.service.SmsInfoService;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author wkangle
 * @className SmsInfoServiceImpl
 * @description 短信信息记录service实现类
 * @time 2021-10-21 09:39:45
 */
@Service("smsInfoService")
@Transactional(rollbackFor = Exception.class)
public class SmsInfoServiceImpl extends ServiceImpl<SmsInfoDao, SmsInfoEntity> implements SmsInfoService {

    private static final Logger logger = LoggerFactory.getLogger(SmsInfoServiceImpl.class);

    @Resource
    private SmsInfoDao smsInfoDao;
    @Autowired
    private DictCodeService dictCodeService;
    @Resource
    private OrderCustomerDao orderCustomerDao;

    @Autowired
    private SendSmsUtil sendSmsUtil;

    /**
     * @param smsInfoEntity
     * @return
     * @description 添加一条记录
     * @author wkangle
     * @time 2021-10-21 09:36:22
     * @exception/throws
     */
    @Override
    public int insert(SmsInfoEntity smsInfoEntity) {
        return smsInfoDao.insert(smsInfoEntity);
    }

    /**
     * @param params 查询条件
     * @return
     * @description 根据查询条件查询短信信息记录
     * @author wkangle
     * @time 2021-10-21 09:37:20
     * @exception/throws
     */
    @Override
    public SmsInfoEntity getOneByParams(Map<String, Object> params) {
        return smsInfoDao.getOneByParams(params);
    }

    /**
     * @param smsInfoEntity
     * @return
     * @description 更新
     * @author wkangle
     * @time 2021-10-21 09:37:13
     * @exception/throws
     */
    @Override
    public int update(SmsInfoEntity smsInfoEntity) {
        return smsInfoDao.update(smsInfoEntity);
    }

    /**
     * @param orderMainEntity 服务单
     * @return
     * @description 发送短信
     * @author wkangle
     * @time 2021/10/21 0021 10:40
     * @exception/throws
     */
    @Override
    public Map<String, Object> send(OrderMainEntity orderMainEntity) {
        /**
         * 短信字典各个字段代表的含义：
         * code 对应服务单主表的状态码
         * 代码描述
         * value 腾讯云模版id
         * value1 开关：0-关，1-开
         * value2/value3/value4/value5 参数
         */
        Map<String, Object> result = new HashMap<>();
        String status = orderMainEntity.getStatus();
        if (PublicUtil.isNotEmpty(status)) { // 判断状态码
            DictCodeEntity smsTemplateDict = dictCodeService.searchAllCodeByTypeCode("smsTemplate", status, 0, null); // 短信模版

            if (PublicUtil.isEmpty(smsTemplateDict)) {
                DictCodeEntity orderStatusDict = dictCodeService.searchAllCodeByTypeCode("orderStatus", status, 0, null); // 状态码对应的状态

                result.put("responseCode", "01");
                result.put("responseMsg", "服务单状态为" + orderStatusDict.getValue() + "的短信模版不存在！");
                return result;
            }

            String templateId = smsTemplateDict.getValue(); // 腾讯云模版id
            String switchStatus = smsTemplateDict.getValue1();// 短信模版的value1字段表示该模版的开关状态，即0-关，1-开
            if (!"1".equals(switchStatus)) {
                result.put("responseCode", "01");
                result.put("responseMsg", "短信模版【" + smsTemplateDict.getCodeDesc() + "】已经关闭，不给客户发送通知短信！");
                return result;
            }

            String orderNo = orderMainEntity.getOrderNo(); // 服务单号

            // 根据服务单号查询客户信息
            Map<String, Object> params = new HashMap<>();
            params.put("orderNo", orderNo);
            OrderCustomerEntity orderCustomerEntity = orderCustomerDao.getOneByParams(params);
            if (PublicUtil.isEmpty(orderCustomerEntity)) {
                result.put("responseCode", "01");
                result.put("responseMsg", "服务单号为" + orderNo + "的客户信息不存在！");
                return result;
            }

            // 根据短信模版和客户信息等参数，转译成短信具体内容
            String username = orderCustomerEntity.getUsername();
            DictCodeEntity serviceItemDict = dictCodeService.searchAllCodeByTypeCode("serviceItem", orderMainEntity.getServiceItem(), 0, null);
            String serviceItem = serviceItemDict.getValue(); // 服务类型

            // 短信参数
            String value2 = smsTemplateDict.getValue2();
            String value3 = smsTemplateDict.getValue3();
            String value4 = smsTemplateDict.getValue4();
            String value5 = smsTemplateDict.getValue5();

            String[] templateParamSet = sendSmsUtil.getTemplateParamSet(value2, value3, value4, value5,
                    username, orderNo, serviceItem, null, null);

            // 保存短信内容到短信信息记录表
            SmsInfoEntity smsInfoEntity = new SmsInfoEntity();
            smsInfoEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            smsInfoEntity.setOrderNo(orderNo);
            smsInfoEntity.setSmsTemplate(templateId);

            String userCode = RequestUtil.getLoginUser().getUserCode();
            Date date = new Date();
            smsInfoEntity.setIsDelete(0);
            smsInfoEntity.setIfNewVersion(1);
            smsInfoEntity.setVersion(1);
            smsInfoEntity.setCreater(userCode);
            smsInfoEntity.setCreateTime(date);
            smsInfoEntity.setUpdater(userCode);
            smsInfoEntity.setUpdateTime(date);

            smsInfoDao.insert(smsInfoEntity);

            // 联系人电话，即接收短信的手机号
            String mobile = orderCustomerEntity.getMobile();
            String[] phoneNumberSet = new String[]{mobile};

            // 发送短信
            String sendResult = sendSmsUtil.send(templateId, phoneNumberSet, templateParamSet);
            if (PublicUtil.isEmpty(sendResult)) {
                result.put("responseCode", "01");
                result.put("responseMsg", "短信发送接口调用异常，请联系管理员");
                return result;
            }
            Map sendStatusSetMap = formatSendResult(sendResult);
            String code = sendStatusSetMap.get("Code").toString();
            Date sendTiem1 = new Date();
            if ("Ok".equals(code)) { // 发送成功

                smsInfoEntity.setSendTime(sendTiem1);
                smsInfoEntity.setSendResult("1");
                smsInfoEntity.setUpdateTime(new Date());
                smsInfoEntity.setSendNum(1);
                smsInfoDao.update(smsInfoEntity);

                result.put("responseCode", "00");
                result.put("responseMsg", "短信发送成功");
                System.out.println("----------第一次发送成功----------");
            } else { // 发送失败，立即再发一次短信
                // 发送短信
                String sendResult2 = sendSmsUtil.send(templateId, phoneNumberSet, templateParamSet);
                Map sendStatusSetMap2 = formatSendResult(sendResult2);
                String code2 = sendStatusSetMap2.get("Code").toString();
                String message2 = sendStatusSetMap2.get("Message").toString();
                Date sendTiem2 = new Date();

                if ("Ok".equals(code2)) {
                    smsInfoEntity.setSendResult("1");
                    System.out.println("----------第二次发送成功----------");
                    result.put("responseCode", "00");
                    result.put("responseMsg", "短信发送成功");

                } else {
                    smsInfoEntity.setSendResult("0");
                    smsInfoEntity.setReason(message2);
                    System.out.println("----------第二次发送失败----------");
                    result.put("responseCode", "01");
                    result.put("responseMsg", message2);

                }
                smsInfoEntity.setSendNum(2);
                smsInfoEntity.setSendTime(sendTiem2);
                smsInfoEntity.setUpdateTime(new Date());
                smsInfoDao.update(smsInfoEntity);
            }

            return result;

        }
        result.put("responseCode", "01");
        result.put("responseMsg", "服务单状态码为空");
        return result;
    }

    private Map formatSendResult(String sendResult) {
        JSONObject jsonObject = JSONObject.parseObject(sendResult);
        JSONArray jsonArray = (JSONArray)jsonObject.get("SendStatusSet");
        JSONObject jsonObj = (JSONObject)jsonArray.get(0);
        return jsonObj.toJavaObject(Map.class);
    }

    public static void main(String[] args) {

        // 日志优化
        String requestBody = "{\"PhoneNumberSet\":[\"13393980987\"],\"SmsSdkAppId\":\"1400587485\",\"TemplateId\":\"1170610\",\"SignName\":\"中轩华宇\",\"TemplateParamSet\":[\"20\"]}";
        String result = "{\"SendStatusSet\":[{\"SerialNo\":\"\",\"PhoneNumber\":\"13393980987\",\"Fee\":0,\"SessionContext\":\"\",\"Code\":\"FailedOperation.TemplateIncorrectOrUnapproved\",\"Message\":\"template is not approved or request content does not match the approved template content\",\"IsoCode\":\"\"}],\"RequestId\":\"2ee7d8f0-ed2e-4a4d-a4cd-05d35deab6f1\"}";
        logger.info("腾讯云发送短信 ==>> \nBody:{}, \nResult:{}", requestBody, result);

        // 解析返回结果
        //String sendResult = "{\"SendStatusSet\":[{\"SerialNo\":\"2433:246981973816353018134918098\",\"PhoneNumber\":\"+8613393980987\",\"Fee\":1,\"SessionContext\":\"\",\"Code\":\"Ok\",\"Message\":\"send success\",\"IsoCode\":\"CN\"}],\"RequestId\":\"e0e50887-6052-4945-84e9-dec60c567033\"}\n";
        //
        //JSONObject jsonObject = JSONObject.parseObject(sendResult);
        //JSONArray jsonArray = (JSONArray)jsonObject.get("SendStatusSet");
        //JSONObject jsonObj = (JSONObject)jsonArray.get(0);
        //
        //Map sendStatusSetMap = jsonObj.toJavaObject(Map.class);
        //System.out.println(sendStatusSetMap);
        //
        //String code = sendStatusSetMap.get("Code").toString();
        //System.out.println(code);
        //
        //String message = sendStatusSetMap.get("Message").toString();
        //System.out.println(message);

        // 服务单尾号
        //String str = "ZX211027010001";
        //System.out.println(str.substring(10, 14));

        // 模版数据替换
        //String words = "尊敬的${username}您好，您的救援已受理。救援单号：${orderNo}，类型：${serviceItem}，我们正在为您安排救援师傅，请您耐心等待，您可关注${officialWechat}官微实时查看救援进展，如有疑问欢迎致电：${officialtelePhone}，${serverName}祝您出行无忧!";
        //
        ////String words = "尊敬的${username}您好，救援师傅准备出发，请您关注${officialWechat}官微实时查看救援进展，如有疑问欢迎致电：${officialtelePhone}，${serverName}祝您出行无忧!";
        //
        //System.out.println("原始字符串是'" + words + "'");
        //System.out.println("replace(\"${username}\",\"张三\")结果：" + words.replace("${username}", "张三"));
        //System.out.println("replace(\"${orderNo}\",\"ZX211021010001\")结果：" + words.replace("${orderNo}", "ZX211021010001 "));
        //System.out.println("replace(\"${serviceItem}\",\"搭电服务\")结果：" + words.replace("${serviceItem}", "搭电服务"));
        //System.out.println("replace(\"${officialWechat}\",\"官微\")结果：" + words.replace("${officialWechat}", "官微"));
        //System.out.println("replace(\"${officialtelePhone}\",\"40000000000\")结果：" + words.replace("${officialtelePhone}", "40000000000"));
        //System.out.println("replace(\"${serverName}\",\"XXX\")结果：" + words.replace("${serverName}", "XXX"));
        //
        //words = words.replace("${username}", "张三")
        //        .replace("${orderNo}", "ZX211021010001 ")
        //        .replace("${serviceItem}", "搭电服务")
        //        .replace("${officialWechat}", "官微")
        //        .replace("${officialtelePhone}", "40000000000")
        //        .replace("${serverName}", "XXX");
        //System.out.println(words);
    }

}
